import smtplib
import os
from email.mime.text import MIMEText
from utils.read_config import ReadConfig
from email.mime.multipart import MIMEMultipart
class SendMail:
    def get_NewReport(self,testreport):
        #获取testreport 目录下的文件返回一个list
        dirs = os.listdir(testreport)
    #对文件list 进行排序 进行增序排列
        dirs.sort()
    #获取序列最后一个元素，即最大的一个元素。
        newreportname = dirs[-1]
        print('The new report name: {0}'.format(newreportname))
        file_new = os.path.join(testreport, newreportname)
        print (file_new)
        return file_new

    def send_Mail(self,file_new):
        config = ReadConfig()
        smtpserver = "smtp.163.com"
        user = "18311447530@163.com"
        sender = "18311447530@163.com"
        pwd = "an1234"
        receiver = "18311447530@163.com"
        port = 25
        f = open(file_new, 'rb')
        # 读取测试报告正文
        mail_body = f.read()
        f.close()
        msg = MIMEMultipart()
        msg['Subject'] = '测试报告'
        msg_file = MIMEText(mail_body, 'html', 'utf-8')
        msg_file['Content-Type'] = 'application/octet-stream'
        msg_file["Content-Disposition"] = 'attachment; filename="TestReport.html"'
        msg.attach(msg_file)
    # 定义发件人，如果不写，发件人为空
        msg['From'] = user
    # 定义收件人，如果不写，收件人为空
        msg['To'] = receiver
        server = smtplib.SMTP()
        server.connect(smtpserver, port)
        server.login(user, pwd)
        server.sendmail(user, receiver, msg.as_string())
        server.close()


if __name__ == '__main__':
        mail=SendMail()
        new_report = mail.get_NewReport("F:\\C++\\untitled3\\reports")
        mail.send_Mail(new_report)

